package org.oslo.mule.transformer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.mule.impl.RequestContext;
import org.mule.transformers.AbstractTransformer;
import org.mule.umo.UMOEventContext;
import org.mule.umo.transformer.TransformerException;
import org.oslo.domain.LocationInfo;
import org.xml.sax.InputSource;

public class GeoResultTransformer extends AbstractTransformer {

	protected Object doTransform(Object payload, String encoding) throws TransformerException {
		byte[] bytePayload = (byte[]) payload;
		ByteArrayOutputStream bOut = new ByteArrayOutputStream();
		try {
			bOut.write(bytePayload);
		} catch(IOException e) {
			e.printStackTrace();
		}
        String result = bOut.toString();
        String coordinates = executeXPath(result, "kml:kml/kml:Response/kml:Placemark/kml:Point/kml:coordinates");
        String[] stringCoordinates = coordinates.split(",");
        double longitude = Double.parseDouble(stringCoordinates[0]);
        double lattitude = Double.parseDouble(stringCoordinates[1]);
        LocationInfo location = new LocationInfo(longitude, lattitude);
        UMOEventContext context = RequestContext.getEventContext();
		location.setSearchIdentifier((String) context.getSession().getProperty("search-identifier"));
		return location;
	}
	
	private static String executeXPath(String input, String xpath) {
        String result = "";
        try {
            XPath path = javax.xml.xpath.XPathFactory.newInstance().newXPath();
            path.setNamespaceContext(getNamespaceContext());
            result = (String)path.evaluate(xpath,new InputSource(new StringReader(input)),XPathConstants.STRING);
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
            Logger.getLogger("global").log(Level.SEVERE, null, ex);
        }
        
        return result;   
    }
    
    private static NamespaceContext getNamespaceContext() {
        return new NamespaceContext() {
                public String getNamespaceURI(String prefix) {
                    if ("kml".equals(prefix)) return "http://earth.google.com/kml/2.0";
                    else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI;
                    else if ("ad".equals(prefix)) return "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0";
                    return XMLConstants.NULL_NS_URI;
                }

                public String getPrefix(String namespaceURI) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                public Iterator getPrefixes(String namespaceURI) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
        };
    }

}
